using Microsoft.Web.WebView2.Core;
using System.Management;

namespace Xbrowser
{
    public partial class MainForm : Form
    {

        HttpListener listener;
        bool quireExit = false;

        private PrintSetting settingDialog = new PrintSetting();

        public MainForm()
        {
            InitializeComponent();
            listener = new HttpListener();
            listener.OnRequest += OnRequestEvent;
            listener.Start();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!quireExit)
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            listener.Stop();
           
        }

        private void CoreWebView2InitializationCompleted(object? sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            webView.Source = new Uri("http://www.x-emr.cn");
            webView.CoreWebView2.NewWindowRequested += NewWindowRequested;
        }


        private void OnRequestEvent(object sender, HttpEventArgs e)
        {
            this.Invoke(new Action(() => {
                var htmlContent = e.Data.ToString();
                printWebView.CoreWebView2.NavigateToString(htmlContent);
            }));
        }


        private void NewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e)
        {
            e.NewWindow = (CoreWebView2)sender;
        }

        private void address_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string url = address.Text;
                if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                {
                    url = "http://" + url;
                    address.Text = url;
                }
                try{ webView.Source = new Uri(url); }catch {}

            }
        }

        CoreWebView2PrintSettings GetrPrintSettings()
        {
            CoreWebView2PrintSettings printSettings = webView.CoreWebView2.Environment.CreatePrintSettings();
            printSettings.PrinterName = settingDialog.DefaultPrintName;
            printSettings.ShouldPrintBackgrounds = settingDialog.printBackground.Checked;
            printSettings.ShouldPrintHeaderAndFooter = settingDialog.printHeadFooter.Checked;
            //printSettings.ShouldPrintSelectionOnly = false;
            printSettings.MarginLeft = 0;
            printSettings.MarginRight = 0;
            printSettings.MarginTop = 0;
            printSettings.MarginBottom = 0;
            printSettings.Copies=  ((int)settingDialog.printCopys.Value);
            printSettings.PageRanges = settingDialog.textPageRanges.Text;
            return printSettings;

        }

        async void PrintToPrinter()
        {

            CoreWebView2PrintSettings printSettings = GetrPrintSettings();
            string title = printWebView.CoreWebView2.DocumentTitle;
            try
            {
                CoreWebView2PrintStatus printStatus = await printWebView.CoreWebView2.PrintAsync(printSettings);
            }
            catch (Exception e)
            {
                MessageBox.Show(this, e.Message);

            }
        }

        async void PrintToPdf()
        {
            CoreWebView2PrintSettings printSettings = webView.CoreWebView2.Environment.CreatePrintSettings();
            printSettings.ShouldPrintBackgrounds = false;
            printSettings.ShouldPrintHeaderAndFooter = false;
            printSettings.MarginLeft = 0;
            printSettings.MarginRight = 0;
            printSettings.MarginTop = 0;
            printSettings.MarginBottom = 0;

            try
            {
                string fileName = Environment.CurrentDirectory + "\\" + new Random().NextInt64().ToString() + ".pdf";
                await webView.CoreWebView2.PrintToPdfAsync(fileName, printSettings);
            }
            catch (Exception e)
            {
                MessageBox.Show(this, e.Message);

            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {

            var result = settingDialog.ShowDialog();
            if (result == DialogResult.OK)
            {

            }

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            webView.CoreWebView2.Reload();
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            webView.CoreWebView2.GoBack();

        }

        private void btnForward_Click(object sender, EventArgs e)
        {
            webView.CoreWebView2.GoForward();
        }

        private void picRefresh_Click(object sender, EventArgs e)
        {
            webView.CoreWebView2.Reload();
        }

        private void webView_SourceChanged(object sender, CoreWebView2SourceChangedEventArgs e)
        {
            address.Text = webView.Source.OriginalString;
        }

        private void printWebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            if (printWebView.Source.OriginalString == "about:blank")
            {
                webView.CoreWebView2.ExecuteScriptAsync("document.querySelector('#_style-mode').href = 'http://127.0.0.1:2023/static/preview.css';");
                PrintToPrinter();
            }
            
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (!this.Visible)
            {
                this.Show();
            }
        }

        private void memuExit_Click(object sender, EventArgs e)
        {
            quireExit = true;
            listener.Stop();
            this.Close();
            Application.Exit();

        }

        private void menuShowMain_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void menuSettings_Click(object sender, EventArgs e)
        {
            settingDialog.ShowDialog();
        }
    }
}